<template>
  <c-back-wrap :loading="loading" go-page="意向客户跟进管理" :before-call-back="$goBackCall" current-page="编辑">
    <c-title title="基本信息">
      <QupFormContainer :column="3">
        <el-form ref="form1" :model="formData" :rules="formRules" label-width="110px">
          <el-form-item prop="customerPhone" label="意向客户电话">
            <span>{{ intendedCustomerDTO.customerPhone }}</span>
          </el-form-item>
          <el-form-item prop="customerName" label="意向客户姓名">
            <el-input v-model.trim="intendedCustomerFormData.customerName" placeholder="意向客户姓名" clearable />
          </el-form-item>
          <el-form-item prop="customerIdcard" label="身份证号">
            <el-input v-model="intendedCustomerFormData.customerIdcard" placeholder="身份证号" clearable />
          </el-form-item>
          <el-form-item prop="customerSex" label="性别">
            <c-common-search-mdm v-model="intendedCustomerFormData.customerSex" cust-doc-code="QY020" :show-dialog="false" />
          </el-form-item>
          <el-form-item prop="customerAge" label="年龄">
            <el-input v-model="intendedCustomerFormData.customerAge" placeholder="年龄" clearable />
          </el-form-item>
          <el-form-item prop="isHaveShop" label="是否有店面">
            <c-dict-select v-model="intendedCustomerFormData.isHaveShop" dict-type-code="BOOLEANS" clearable placeholder="是否有店面" style="width:100%" />
          </el-form-item>
          <el-form-item prop="shopArea" label="店面总面积(㎡)">
            <el-input v-model="intendedCustomerFormData.shopArea" v-number.float="2" placeholder="店面总面积(㎡)" clearable />
          </el-form-item>
          <el-form-item prop="intendedBusiness" label="意向经营业务">
            <c-common-search-mdm v-model="intendedCustomerFormData.intendedBusiness" multiple cust-doc-code="QY037" />
          </el-form-item>
          <el-form-item prop="intendedCity" label="意向加盟城市">
            <el-input v-model="intendedCustomerFormData.intendedCity" placeholder="意向加盟城市" clearable />
          </el-form-item>
          <el-form-item prop="agencyCode" label="所属办事处">
            <!-- 筛选范围为启用状态的所有办事处 -->
            <c-common-search-office
              v-model="intendedCustomerFormData.agencyCode"
              :label.sync="intendedCustomerFormData.agencyName"
            />
          </el-form-item>
          <el-form-item prop="customerSource" label="客户来源">
            <c-dict-select v-model="intendedCustomerFormData.customerSource" dict-type-code="CTM_TOBE_CUSTOMER_DATA_FROM" clearable placeholder="客户来源" style="width:100%" />
          </el-form-item>
          <el-form-item prop="specialRemarks" label="特别备注" :span="24">
            <span>{{ intendedCustomerDTO.specialRemarks }}</span>
          </el-form-item>
          <el-form-item prop="channel" label="来源渠道">
            <c-dict-range-view :value="intendedCustomerFormData.channel" dict-type-code="CTM_POTENTIAL_CUSTOMER_SOURCE" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item prop="allotTime" label="意向客户分配时间">
            <span>{{ intendedCustomerDTO.allotTime }}</span>
          </el-form-item>
          <el-form-item prop="createBy" label="创建人">
            <span>{{ intendedCustomerDTO.createBy }}</span>
          </el-form-item>
          <el-form-item prop="createTime" label="创建时间">
            <span>{{ intendedCustomerDTO.createTime }}</span>
          </el-form-item>
          <el-form-item prop="lastUpdateBy" label="修改人">
            <span>{{ intendedCustomerDTO.lastUpdateBy }}</span>
          </el-form-item>
          <el-form-item prop="lastUpdateTime" label="修改时间">
            <span>{{ intendedCustomerDTO.lastUpdateTime }}</span>
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="跟进明细">
      <QupFormContainer :column="3">
        <el-form ref="form2" :model="formData" :rules="formRules" label-width="130px">
          <el-form-item prop="followUpType" label="跟进方式">
            <c-dict-select v-model="ctmFranchiseMarketFormData.followUpType" dict-type-code="CTM_FOLLOW_UP_TYPE" clearable placeholder="跟进方式" style="width:100%" />
          </el-form-item>
          <el-form-item prop="investmentManagerId" label="招商经理">
            <span>{{ ctmFranchiseMarketFormData.managerName }}</span>
          </el-form-item>
          <el-form-item prop="intendedLevel" label="意向等级">
            <Tip>
              <div slot="tip">
                A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约；<br>
                B类：明确与全友合作意向，但可能资金不足或口岸不达标；<br>
                C类：有明确投资意向，对全友或其他竞品品牌；
              </div>
              <c-dict-select v-model="intendedCustomerFormData.intendedLevel" dict-type-code="CTM_INTENTION_LEVEL" clearable placeholder="意向等级" style="width:100%" />
            </Tip>
          </el-form-item>
          <el-form-item prop="industryQualification" label="现经营品牌/行业资历" :span="24">
            <el-input v-model="intendedCustomerFormData.industryQualification" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="现经营品牌/行业资历" clearable />
          </el-form-item>
          <el-form-item prop="intendedShopArea" label="意向开店面积(㎡)">
            <el-input v-model="intendedCustomerFormData.intendedShopArea" v-number.float="2" placeholder="意向开店面积(㎡)" clearable />
          </el-form-item>
          <el-form-item prop="description" label="跟进说明" :span="24">
            <el-input v-model="ctmFranchiseMarketFormData.description" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="跟进说明" clearable />
          </el-form-item>
          <el-form-item prop="intendedMerchantDescription" label="意向商家情况描述" :span="24">
            <el-input v-model="ctmFranchiseMarketFormData.intendedMerchantDescription" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="意向商家情况描述" clearable />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="特许经营市场">
      <QupFormContainer :column="3">
        <el-form ref="form3" :model="formData" :rules="formRules" label-width="120px">
          <el-form-item prop="marketCode" label="市场">
            <c-common-search-market-no-ref
              v-model="ctmFranchiseMarketFormData.marketCode"
              :label.sync="ctmFranchiseMarketFormData.marketName"
              :province-code.sync="ctmMarketFormData.provinceCode"
              :province-id.sync="ctmMarketFormData.provinceId"
              :province-name.sync="ctmMarketFormData.provinceName"
              :city-id.sync="ctmMarketFormData.cityId"
              :city-code.sync="ctmMarketFormData.cityCode"
              :city-name.sync="ctmMarketFormData.cityName"
              :district-id.sync="ctmMarketFormData.districtId"
              :district-code.sync="ctmMarketFormData.districtCode"
              :district-name.sync="ctmMarketFormData.districtName"
              :street-id.sync="ctmMarketFormData.streetId"
              :street-code.sync="ctmMarketFormData.streetCode"
              :street-name.sync="ctmMarketFormData.streetName"
              :city-level.sync="ctmMarketFormData.cityLevel"
              :market-type.sync="ctmMarketFormData.marketType"
              :is-old-merchant.sync="ctmMarketFormData.isOldMerchant"
            />
          </el-form-item>
          <el-form-item prop="provinceName" label="省份">
            <span>{{ ctmMarketFormData.provinceName }}</span>
          </el-form-item>
          <el-form-item prop="cityName" label="城市">
            <span>{{ ctmMarketFormData.cityName }}</span>
          </el-form-item>
          <el-form-item prop="districtName" label="区县">
            <span>{{ ctmMarketFormData.districtName }}</span>
          </el-form-item>
          <el-form-item prop="streetName" label="乡镇/街道">
            <span>{{ ctmMarketFormData.streetName }}</span>
          </el-form-item>
          <el-form-item prop="cityLevel" label="城市级别">
            <c-dict-range-view :value="ctmMarketFormData.cityLevel" dict-type-code="CITY_LEVEL" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item prop="marketType" label="市场类型">
            <c-dict-range-view :value="ctmMarketFormData.marketType" dict-type-code="TOBE_MARKET_TYPE" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item prop="isOldMerchant" label="是否有老商家">
            <c-dict-range-view :value="ctmMarketFormData.isOldMerchant" dict-type-code="BOOLEANS" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item prop="isSite" label="是否有场地">
            <c-dict-select v-model="ctmFranchiseMarketFormData.isSite" dict-type-code="BOOLEANS" clearable placeholder="是否有场地" style="width:100%" />
          </el-form-item>
          <el-form-item prop="address" label="场地详细地址" :span="24">
            <el-input v-model="ctmFranchiseMarketFormData.address" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="场地详细地址" clearable />
          </el-form-item>
          <el-form-item prop="isPayEarmestMoney" label="是否缴纳意向保证金" label-width="120px">
            <el-switch v-model="ctmFranchiseMarketFormData.isPayEarmestMoney" active-value="1" inactive-value="0" />
          </el-form-item>
          <el-form-item v-if="[1,'1'].includes(ctmFranchiseMarketFormData.isPayEarmestMoney)" prop="payEarmestMoneyTime" label="意向保证金缴纳时间" label-width="130px">
            <el-date-picker v-model="ctmFranchiseMarketFormData.payEarmestMoneyTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" clearable />
          </el-form-item>
          <el-form-item prop="isAgencyProblemHanding" label="是否有需要办事处协助解决的问题" label-width="200px" :span="24">
            <el-switch v-model="ctmFranchiseMarketFormData.isAgencyProblemHanding" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item v-if="[1,'1'].includes(ctmFranchiseMarketFormData.isAgencyProblemHanding)" prop="agencyProblemHandingMsg" label="需要办事处协助解决的问题说明" label-width="200px" :span="24">
            <el-input v-model="ctmFranchiseMarketFormData.agencyProblemHandingMsg" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="需要办事处协助解决的问题说明" clearable />
          </el-form-item>
          <el-form-item prop="investmentCommitment" label="招商政策及前期的招商承诺" label-width="200px" :span="24">
            <el-input v-model="ctmFranchiseMarketFormData.investmentCommitment" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="招商政策及前期的招商承诺" clearable />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="marketFiles" label="市场附件信息" :span="24">
            <c-file-list v-model="ctmFranchiseMarketFormData.marketFiles" direct-del :model-id="id" view-type="list" type-code="ACCESS049" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存</c-button>
      <c-button type="primary" @click="handleHandover">交接</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { potentialCustomerFollowUpDetail, potentialCustomerFollowUpEdit, potentialCustomerFollowUpSubmit } from '@/api/channelTask2/potentialCustomerFollowUp'
import Tip from '@/components/Tip'
export default {
  name: 'Edit',
  components: {
    Tip
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      intendedCustomerFormData: {
        customerPhone: '',
        customerName: '',
        customerIdcard: '',
        isHaveShop: '',
        shopArea: '',
        intendedBusiness: '',
        intendedCity: '',
        agencyCode: '',
        agencyName: '',
        customerSex: '',
        customerAge: '',
        customerSource: '',
        specialRemarks: '',
        channel: '',
        createBy: '',
        createTime: '',
        lastUpdateBy: '',
        lastUpdateTime: ''
      },
      ctmFranchiseMarketFormData: {
        followUpType: '',
        description: '',
        intendedMerchantDescription: '',
        marketCode: '',
        marketName: '',
        address: '',
        isPayEarmestMoney: '',
        payEarmestMoneyTime: '',
        isAgencyProblemHanding: '',
        agencyProblemHandingMsg: '',
        investmentCommitment: '',
        isSite: '',
        managerName: '',
        marketFiles: []
      },
      ctmMarketFormData: {
        provinceCode: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityCode: '',
        cityName: '',
        districtId: '',
        districtCode: '',
        districtName: '',
        streetId: '',
        streetCode: '',
        streetName: '',
        cityLevel: '',
        marketType: '',
        isOldMerchant: ''
      },
      loading: false
    }
  },
  computed: {
    formRules() {
      return {
        agencyProblemHandingMsg: [{ required: [1, '1'].includes(this.ctmFranchiseMarketFormData.isAgencyProblemHanding), message: '请输入需要办事处协助解决的问题说明', trigger: 'change' }],
        payEarmestMoneyTime: [{ required: [1, '1'].includes(this.ctmFranchiseMarketFormData.isPayEarmestMoney), message: '请选择意向保证金缴纳时间', trigger: 'change' }],
        intendedMerchantDescription: [{ required: true, message: '请输入意向商家情况描述', trigger: 'change' }],
        address: [{ required: [1, '1'].includes(this.ctmFranchiseMarketFormData.isSite), message: '请输入场地详细地址', trigger: 'change' }],
        customerSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        customerAge: [{ required: true, message: '请输入年龄', trigger: 'change' }]
        // marketFiles: [{ required: true, validator: (r, v, c) => {
        //   if (!v || v.length <= 0) {
        //     c(new Error('请上传市场附件'))
        //   } else {
        //     c()
        //   }
        // }, trigger: 'change' }]
      }
    },
    ctmFranchiseMarketDTO() {
      return this.detail.ctmFranchiseMarketDTO || {}
    },
    ctmMarketBuildFollowUpResultDTO() {
      return this.detail.ctmMarketBuildFollowUpResultDTO || {}
    },
    intendedCustomerDTO() {
      return this.detail.intendedCustomerDTO || {}
    },
    ctmMarketDTO() {
      return this.detail.ctmMarketDTO || {}
    },
    marketFiles() {
      return this.detail.marketFiles || []
    },
    formData() {
      const { intendedCustomerFormData,
        ctmFranchiseMarketFormData,
        ctmMarketFormData } = this
      return Object.assign({}, intendedCustomerFormData,
        ctmFranchiseMarketFormData,
        ctmMarketFormData)
    }
  },
  created() {
    this.getDetail()
  },
  methods: {
    getDetail() {
      return potentialCustomerFollowUpDetail(this.id).then(res => {
        const intendedBusiness = res.data.intendedCustomerDTO.intendedBusiness || ''
        res.data.intendedCustomerDTO.intendedBusiness = intendedBusiness.split(',')
        this.intendedCustomerFormData = res.data.intendedCustomerDTO || {}
        this.intendedCustomerFormData.customerSex = (this.intendedCustomerFormData.customerSex || '').toString()
        this.ctmFranchiseMarketFormData = res.data.ctmFranchiseMarketDTO || {}
        this.ctmMarketFormData = res.data.ctmMarketDTO || {}
        this.$set(this.ctmFranchiseMarketDTO, 'marketFiles', res.data.marketFiles || [])
        this.detail = JSON.parse(JSON.stringify(res.data))
        this.$nextTick(this.clearValidate)
      })
    },
    clearValidate() {
      const keys = 'form1 form2 form3'.split(' ')
      keys.forEach(k => {
        if (this.$refs[k] && this.$refs[k].clearValidate) {
          this.$refs[k].clearValidate()
        }
      })
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    async getParams(validate = false) {
      if (validate) {
        const { form1, form2, form3 } = this.$refs
        await form1.validate()
        await form2.validate()
        await form3.validate()
      }
      // 处理数据
      const data = {
        ctmFranchiseMarketDTO: { ...this.ctmFranchiseMarketDTO, ...this.ctmFranchiseMarketFormData },
        intendedCustomerDTO: { ...this.intendedCustomerDTO, ...this.intendedCustomerFormData },
        ctmMarketDTO: { ...this.ctmMarketDTO, ...this.ctmMarketFormData },
        marketFiles: this.$getFiles(this.ctmFranchiseMarketFormData.marketFiles || [])
      }
      delete data.ctmFranchiseMarketDTO.marketFiles
      data.intendedCustomerDTO.intendedBusiness = (data.intendedCustomerDTO.intendedBusiness || []).join(',')
      if (![1, '1'].includes(data.ctmFranchiseMarketDTO.isPayEarmestMoney)) {
        data.ctmFranchiseMarketDTO.payEarmestMoneyTime = ''
      }
      if (![1, '1'].includes(data.ctmFranchiseMarketDTO.isAgencyProblemHanding)) {
        data.ctmFranchiseMarketDTO.agencyProblemHandingMsg = ''
      }
      if (![1, '1'].includes(data.ctmFranchiseMarketDTO.isSite)) {
        data.ctmFranchiseMarketDTO.address = ''
      }

      return data
    },
    handleSave() {
      return this.getParams().then(data => {
        return potentialCustomerFollowUpEdit(data).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleHandover() {
      return this.getParams(true).then(data => {
        return potentialCustomerFollowUpSubmit(data).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    }
  }
}
</script>
